package middleware

import (
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"net/http"
	"runtime/debug"
	"zerorpc/util/errors"
)

func WithExceptionMiddleware(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if err := recover(); err != nil {
				fmt.Println(err)
				logx.WithContext(r.Context()).Error(fmt.Sprintf("%v\n%s", err, debug.Stack()))
				errors.ResponseHandler(w, nil, &errors.ServerError)
			}
		}()
		next(w, r)
	}
}
